package com.sevenstudio.adu.gasing.state;

import org.andengine.engine.Engine.EngineLock;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.util.FPSLogger;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants;
import org.andengine.input.touch.TouchEvent;

import android.R.anim;
import android.view.KeyEvent;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.sevenstudio.adu.gasing.bluetooth.BT_Server_Client;
import com.sevenstudio.adu.gasing.define.GameEngineConfiguration;
import com.sevenstudio.adu.gasing.define.iGameDefines;
import com.sevenstudio.adu.gasing.define.iServer_Data;
import com.sevenstudio.adu.gasing.element.AAnimatedSprite;
import com.sevenstudio.adu.gasing.element.ABackground;
import com.sevenstudio.adu.gasing.element.AMusic;
import com.sevenstudio.adu.gasing.element.ARectangle;
import com.sevenstudio.adu.gasing.element.AScene;
import com.sevenstudio.adu.gasing.element.ASprite;
import com.sevenstudio.adu.gasing.engine.Anchor;
import com.sevenstudio.adu.gasing.engine.GameEngine;
import com.sevenstudio.adu.gasing.engine.Utils;
import com.sevenstudio.adu.gasing.object.Enemy;
import com.sevenstudio.adu.gasing.object.Item;
import com.sevenstudio.adu.gasing.object.Mc;

public class State_Game_Play implements iGameDefines
{
	float			benturanX, benturanY;
	
	String			fix_A, fix_B;
	static boolean	resume;

	public static Mc		mc;
	public static Mc		mc2;
	public static Enemy	enemy;
	public static AScene scene;
	ABackground		bg;
	AMusic			benturan, gasing1, gasing2, vs;
	ASprite			sprBenturan, tutor, btnPause, vsBg, vsMata, btnFight, btnTenaga;
	ASprite[]		bgIcon	= new ASprite[2], barBg = new ASprite[2],
			 barPanah = new ASprite[2],
			icon = new ASprite[2], vsIcon = new ASprite[2],
			vsPanah = new ASprite[3];
	
	AAnimatedSprite anim_asap;
	
	public static ASprite[] barHealth = new ASprite[2];
	

	ASprite bar_tenaga;
	ASprite baner_tanaga;
	ASprite tutor_tenaga;
	
	ASprite txt_P1, txt_P2, txt_cpu;

	ARectangle		rec;
	GameEngine		engine;

	public static float speedX = 0;
	public static float speedY = 0;
	public static float X1, Y1, X2, Y2, bar1, bar2, perlambat1, perlambat2;
	public static boolean startGame, isPause;
	Item item;
	
	private int bar, time, action;
	boolean stop_bar = false;
	boolean activeBar = false;
	
	private boolean startItem;
	
	public static PhysicsWorld	world	= new PhysicsWorld(new Vector2(0, 0), false);
	
	Vector2 vMc1, vMc2;
	
	public State_Game_Play(GameEngine engine)
	{
		this.engine = engine;
		
		scene = new AScene(0);
		gasing1 = new AMusic(engine, SFX_GAME, SFX_GASING1);
		vs = new AMusic(engine, SFX_GAME, SFX_GAME_VS);
		benturan = new AMusic(engine, SFX_GAME, SFX_GAME_BENTURAN);
		tutor = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_TUTOR);
		btnPause = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_PAUSE);
		vsBg = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_BG);
		vsMata = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_MATA);
		btnFight = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_FIGHT);
		sprBenturan = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_BENTURAN);
		sprBenturan.theSprite().setVisible(false);
		
		anim_asap = new AAnimatedSprite(engine, iGameDefines.ANIM_EFFECT, 0);
		anim_asap.theSprite().setVisible(false);
		
		for (int i = 0; i < 2; i++)
		{
			bgIcon[i] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_BG_ICON_LEFT + i);
			barBg[i] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_BAR_BG_LEFT + i);
			barHealth[i] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_BAR_HEALTH_LEFT + i);
			barPanah[i] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_BAR_PANAH_LEFT + i);
		}

		for (int i = 0; i < 3; i++)
		{

			vsPanah[i] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_PANAH1 + i);
		}


			
			baner_tanaga = new ASprite(engine, iGameDefines.SPR_START_CARIEER, 1);
			bar_tenaga = new ASprite(engine, iGameDefines.SPR_START_CARIEER, 0);
			
			
			btnTenaga = new ASprite(engine, iGameDefines.SPR_START_CARIEER, 2);
			btnTenaga.theSprite().setY(Utils.GetRatioHeight(300));
			tutor_tenaga = new ASprite(engine, iGameDefines.SPR_START_CARIEER, 3);
			
		txt_P1 = new ASprite(engine, iGameDefines.SPR_TEXT_PLAY, 0);
		txt_P2 = new ASprite(engine, iGameDefines.SPR_TEXT_PLAY, 1);
		txt_cpu = new ASprite(engine, iGameDefines.SPR_TEXT_PLAY, 2);
			
		rec = new ARectangle(engine, iGameDefines.RECT_GAME, 6);
		
		engine.getEngine().registerUpdateHandler(new FPSLogger());
		
		world.setContactListener(new ContactListener()
		{
			public void preSolve(Contact contact, Manifold oldManifold)
			{}
			
			public void postSolve(Contact contact, ContactImpulse impulse)
			{}
			
			public void endContact(Contact contact)
			{}
			
			public void beginContact(Contact contact)
			{
				if (contact.getFixtureA().getBody().getUserData() != null
						&& contact.getFixtureB().getBody().getUserData() != null)
				{
					fix_A = contact.getFixtureA().getBody().getUserData()
							.toString();
					fix_B = contact.getFixtureB().getBody().getUserData()
							.toString();
				}
				
				if (fix_A.contains("mc") && fix_B.contains("mc"))
				{
					benturan();
				}
				
			}
		});
		
		
		item = new Item(engine, scene, iGameDefines.SPRITE_ITEM, iGameDefines.SPRITE_ITEM.length);
		
	}
	
	public void Init()

	{
		if(BT_Server_Client.isBluetooth)
			scene.theScene().detachChildren();
		
		startGame = isPause = false;
		bar1 = bar2 = Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT + 0].getH());
		
		engine.SetGameScene(scene);
		
		bg = new ABackground(engine, SPRITE_GAME, iServer_Data.INDEX_ARENA);

		if(BT_Server_Client.isBluetooth)
		{
			if(BT_Server_Client.isServer)
			{
				mc = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_MC, world, true);
				mc2 = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_RIVAL, world, false);
			}
			else
			{
				mc = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_MC, world, false);
				mc2 = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_RIVAL, world, true);
			}
		}
		else
		{
			mc = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_MC, world, true);
			enemy = new Enemy(engine, SPRITE_GASING, iServer_Data.INDEX_RIVAL, world, mc);		
		}
		
		vsIcon[0] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_ACEH_KIRI + iServer_Data.INDEX_MC * 2);
		vsIcon[1] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_ACEH_KANAN + iServer_Data.INDEX_RIVAL * 2);
		icon[0] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_ICON_ACEH_LEFT + iServer_Data.INDEX_MC * 2);
		icon[1] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_ICON_ACEH_RIGHT + iServer_Data.INDEX_RIVAL * 2);

		
		if(BT_Server_Client.isBluetooth)
		{
			if(BT_Server_Client.isServer)
			{
				mc = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_MC, world, true);
				mc2 = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_RIVAL, world, false);
			}
			else
			{
				mc = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_MC, world, false);
				mc2 = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_RIVAL, world, true);
			}
		}
		
		
		
		if (GameEngineConfiguration.ModeSelected == MODE_CAREER)
		{
			mc = new Mc(engine, SPRITE_GASING, GASING_DEFAULT, world, true);
			enemy = new Enemy(engine, SPRITE_GASING, GameEngineConfiguration.Level_Career, world, mc);
			
			Utils.TRACE("Gasing Default "+GASING_DEFAULT);
			
			vsIcon[0] = new ASprite(engine, SPRITE_MC_CAREER, DEFAULT_GASING_VS);
			vsIcon[1] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_YOGYA_KANAN + GameEngineConfiguration.Level_Career * 2);
			icon[0] = new ASprite(engine, SPRITE_MC_CAREER, DEFAULT_GASING_ICON);
			icon[1] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_ICON_YOGYA_RIGHT + GameEngineConfiguration.Level_Career * 2);
		
			
		}
		else 
		{
			mc = new Mc(engine, SPRITE_GASING, iServer_Data.INDEX_MC, world, true);
			enemy = new Enemy(engine, SPRITE_GASING, iServer_Data.INDEX_RIVAL, world, mc);	
			
			vsIcon[0] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_YOGYA_KIRI + iServer_Data.INDEX_MC * 2);
			vsIcon[1] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_VS_YOGYA_KANAN + iServer_Data.INDEX_RIVAL * 2);
			icon[0] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_ICON_YOGYA_LEFT + iServer_Data.INDEX_MC * 2);
			icon[1] = new ASprite(engine, SPRITE_GAME, SPRITE_GAME_ICON_YOGYA_RIGHT + iServer_Data.INDEX_RIVAL * 2);
		}
		
		resume = false;
		
		mc.reset();
		if(BT_Server_Client.isBluetooth)
			mc2.reset();
		else
			enemy.reset();
		
		vsPanah[0].SetPos(SPRITE_GAME[SPRITE_GAME_VS_PANAH1].getX() + (SPRITE_GASING[iServer_Data.INDEX_MC].getBerat() - SPRITE_GASING[iServer_Data.INDEX_RIVAL].getBerat()) * 20, SPRITE_GAME[SPRITE_GAME_VS_PANAH1].getY(), Anchor.CENTER);
		vsPanah[1].SetPos(SPRITE_GAME[SPRITE_GAME_VS_PANAH2].getX() + (SPRITE_GASING[iServer_Data.INDEX_MC].getPutaran() - SPRITE_GASING[iServer_Data.INDEX_RIVAL].getPutaran()) * 20, SPRITE_GAME[SPRITE_GAME_VS_PANAH2].getY(), Anchor.CENTER);
		vsPanah[2].SetPos(SPRITE_GAME[SPRITE_GAME_VS_PANAH3].getX() + (SPRITE_GASING[iServer_Data.INDEX_MC].getKecepatan() - SPRITE_GASING[iServer_Data.INDEX_RIVAL].getKecepatan()) * 20, SPRITE_GAME[SPRITE_GAME_VS_PANAH3].getY(), Anchor.CENTER);


		final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0,
				0f, 0f);
		
		for (int i = 0; i < 4; i++)
		{
			ARectangle rec = new ARectangle(engine, RECT_GAME, i);
			PhysicsFactory.createBoxBody(world, rec.theRect(),
					BodyType.StaticBody, wallFixtureDef).setUserData("wall");
			engine.SceneAttach(scene, rec);
		}

		engine.SceneAttach(scene, bg);
		scene.theScene().attachChild(mc.getShadow());
		
		if(BT_Server_Client.isBluetooth)
		{
			scene.theScene().attachChild(mc2.getShadow());
			engine.SceneAttach(scene, mc2);
		}
		else
		{
			scene.theScene().attachChild(enemy.getShadow());
//			engine.SceneAttach(scene, enemy.getEffect());
			engine.SceneAttach(scene, enemy);
			engine.SceneAttach(scene, enemy.getText());
			
		}
		
		engine.SceneAttach(scene, mc);
		
		if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_CAREER)
		{
			for(int i=0; i < iGameDefines.SPRITE_EFFECT_ITEM.length; i++)
			{
				mc.getSprite().attachChild(mc.getItemEffect(i));
				mc.getItemEffect(i).setVisible(false);
				enemy.getSprite().attachChild(enemy.getItemEffect(i));
				enemy.getItemEffect(i).setVisible(false);
			}
		}
		

		for (int i = 0; i < 2; i++)
		{
						
			barHealth[i].theSprite().setHeight(Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT + i].getH()));
			
			engine.SceneAttach(scene, barBg[i]);
			engine.SceneAttach(scene, barHealth[i]);
			engine.SceneAttach(scene, barPanah[i]);
			engine.SceneAttach(scene, bgIcon[i]);
			engine.SceneAttach(scene, icon[i]);
			
		
		}
		
		vs.Play();
		
		if(GameEngineConfiguration.ModeSelected == MODE_MULTI)
		{
			engine.SceneAttach(scene, txt_P1);
			engine.SceneAttach(scene, txt_P2);
		}
		else if(GameEngineConfiguration.ModeSelected == MODE_CAREER)
		{
			engine.SceneAttach(scene, txt_P1);
			engine.SceneAttach(scene, txt_cpu);
		}
		else
		{
			engine.SceneAttach(scene, txt_P1);
			engine.SceneAttach(scene, txt_cpu);
		}

		engine.SceneAttach(scene, btnPause);
		engine.SceneAttach(scene, rec);
		engine.SceneAttach(scene, vsBg);
		for (int i = 0; i < 3; i++)
		{
			engine.SceneAttach(scene, vsPanah[i]);
			if(i < 2)
				engine.SceneAttach(scene, vsIcon[i]);
		}
		engine.SceneAttach(scene, vsMata);
		
		if (BT_Server_Client.isServer || !BT_Server_Client.isBluetooth)
		{
			engine.SceneAttach(scene, btnFight);
			scene.theScene().registerTouchArea(btnFight.theSprite());
		}
		

		startItem = false;
		
		if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_CAREER)
		{
			
			engine.SceneAttach(scene, bar_tenaga);
			bar_tenaga.theSprite().setWidth(0);
			item.resetItem();
		}
				
		
		engine.SceneAttach(scene, sprBenturan);
		engine.SceneAttach(scene, anim_asap);
		
		scene.theScene().registerTouchArea(btnPause.theSprite());
		scene.theScene().registerTouchArea(btnTenaga.theSprite());
		scene.theScene().setOnSceneTouchListener(engine);
		scene.theScene().setOnAreaTouchListener(engine);
		scene.theScene().registerUpdateHandler(world);

		barHealth[0].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getY(), Anchor.BOTTOM_LEFT);
		barHealth[1].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getY(), Anchor.BOTTOM_RIGHT);
		
		barPanah[0].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_LEFT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_PANAH_LEFT].getY(), Anchor.BOTTOM_LEFT);
		barPanah[1].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_RIGHT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_PANAH_RIGHT].getY(), Anchor.BOTTOM_RIGHT);
		
//		gasing1.Play();
//		vs.Play();
		

	}
	
	public void Update()
	{	
	
		
		if(resume)
		{
			resume = false;
			gasing1.Play();
			scene.theScene().registerUpdateHandler(world);

		}
		
		if(isPause)
		{
			isPause = false;
			pause();
		}
		
		if (startGame)
		{
		
			
			gasing1.Play();
			
			mc.setPlay(true);
			
			if (BT_Server_Client.isBluetooth)
				mc2.setPlay(true);
			else
				enemy.setPlay(true);
			vsBg.DetachSelf();
			for (int i = 0; i < 3; i++)
			{
				vsPanah[i].DetachSelf();
				if (i < 2) vsIcon[i].DetachSelf();
			}
			btnFight.DetachSelf();
			vsMata.DetachSelf();
			rec.theRect().detachSelf();
		
			
		mc.onUpdate();

		if(BT_Server_Client.isBluetooth)
		{
			mc2.onUpdate();
			mc2.move(speedX, speedY);
			
			if(BT_Server_Client.isServer)
			{
				vMc1 = mc.getBody().getTransform().getPosition();
				vMc2 = mc2.getBody().getTransform().getPosition();
				
				engine.server_Client.sendMessage("X1," +vMc1.x+ ","+vMc1.y+ ","+vMc2.x+ ","+vMc2.y);
//				engine.server_Client.sendMessage("Y1," +mc.getBody().getTransform().getPosition().y);
//				engine.server_Client.sendMessage("X2," +mc2.getBody().getTransform().getPosition().x);
//				engine.server_Client.sendMessage("Y2," +mc2.getBody().getTransform().getPosition().y);
			}
			else
			{
				mc.getBody().setTransform(X1, Y1, 0);
				mc2.getBody().setTransform(X2, Y2, 0);
				
//				mc.getSprite().setPosition(X1
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc.getSprite().getWidth() / 2, Y1
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc.getSprite().getHeight() / 2);
//				
//				mc2.getSprite().setPosition(X2
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc2.getSprite().getWidth() / 2, Y2
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc2.getSprite().getHeight() / 2);
				
//				mc.getSprite().setPosition(X1, Y1);
//				mc2.getSprite().setPosition(X2, Y2);
				
				barHealth[0].theSprite().setHeight(bar1);
				barHealth[1].theSprite().setHeight(bar2);
				
				if (barHealth[0].theSprite().getHeight() <= 0)
				{
					barHealth[0].theSprite().setHeight(0);
					scene.theScene().unregisterUpdateHandler(world);
					gasing1.Stop();
					engine.SetNextMessageState(0);
					
					if (BT_Server_Client.isBluetooth && !BT_Server_Client.isServer)
					{
						engine.SetNextGameState(iGameDefines.GAME_STATE_WIN);
					}						
					else
						engine.SetNextGameState(iGameDefines.GAME_STATE_OVER);
				}
				else if (barHealth[1].theSprite().getHeight() <= 0)
				{
					barHealth[1].theSprite().setHeight(0);
					scene.theScene().unregisterUpdateHandler(world);
					gasing1.Stop();
					engine.SetNextMessageState(0);
					
					if (BT_Server_Client.isBluetooth && !BT_Server_Client.isServer)
					{
						engine.SetNextGameState(iGameDefines.GAME_STATE_OVER);
					}
					else
						engine.SetNextGameState(iGameDefines.GAME_STATE_WIN);
					
				}
				barHealth[0].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getY(), Anchor.BOTTOM_LEFT);
				barHealth[1].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getY(), Anchor.BOTTOM_RIGHT);
				
				barPanah[0].theSprite().setPosition(
					Utils.GetAnchorX(barPanah[0].theSprite().getWidth(), Anchor.BOTTOM_LEFT) + Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_LEFT].getX()),
					Utils.GetAnchorY(barPanah[0].theSprite().getHeight(), Anchor.BOTTOM_LEFT) - barHealth[0].theSprite().getHeight() - Utils.GetRatio(50));
				barPanah[1].theSprite()
					.setPosition(
						Utils.GetAnchorX(barPanah[1].theSprite().getWidth(), Anchor.BOTTOM_RIGHT) +
							Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_RIGHT].getX()),
						Utils.GetAnchorY(barPanah[1].theSprite().getHeight(), Anchor.BOTTOM_RIGHT) - barHealth[1].theSprite().getHeight() - Utils.GetRatio(50));
				

				mc.perlambat(perlambat1);
				mc2.perlambat(perlambat2);
			}
		}
		else
		{
		
			enemy.onUpdate();
		}
		

		if(startItem)
		{
			if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_CAREER)
			{
				item.onUpdate();
			}
		}
		
		
		if(BT_Server_Client.isBluetooth)
		{
			mc2.onUpdate();
			mc2.move(speedX, speedY);
		}
		else
			enemy.onUpdate();

		
		if(BT_Server_Client.isBluetooth)
		{
			mc2.onUpdate();
			mc2.move(speedX, speedY);
			
			if(BT_Server_Client.isServer)
			{
				engine.server_Client.sendMessage("X1," +mc.getBody().getTransform().getPosition().x);
				engine.server_Client.sendMessage("Y1," +mc.getBody().getTransform().getPosition().y);
				engine.server_Client.sendMessage("X2," +mc2.getBody().getTransform().getPosition().x);
				engine.server_Client.sendMessage("Y2," +mc2.getBody().getTransform().getPosition().y);
			}
			else
			{
				mc.getBody().setTransform(X1, Y1, 0);
				mc2.getBody().setTransform(X2, Y2, 0);
				
//				mc.getSprite().setPosition(X1
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc.getSprite().getWidth() / 2, Y1
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc.getSprite().getHeight() / 2);
//				
//				mc2.getSprite().setPosition(X2
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc2.getSprite().getWidth() / 2, Y2
//					* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT
//					- mc2.getSprite().getHeight() / 2);
				
//				mc.getSprite().setPosition(X1, Y1);
//				mc2.getSprite().setPosition(X2, Y2);
				
				barHealth[0].theSprite().setHeight(bar1);
				barHealth[1].theSprite().setHeight(bar2);
				
				if (barHealth[0].theSprite().getHeight() <= 0)
				{
					barHealth[0].theSprite().setHeight(0);
					scene.theScene().unregisterUpdateHandler(world);
					gasing1.Stop();
					engine.SetNextMessageState(0);
					
					if (BT_Server_Client.isBluetooth && !BT_Server_Client.isServer)
					{
						engine.SetNextGameState(iGameDefines.GAME_STATE_WIN);
					}						
					else
						engine.SetNextGameState(iGameDefines.GAME_STATE_OVER);
				}
				else if (barHealth[1].theSprite().getHeight() <= 0)
				{
					barHealth[1].theSprite().setHeight(0);
					scene.theScene().unregisterUpdateHandler(world);
					gasing1.Stop();
					engine.SetNextMessageState(0);
					
					if (BT_Server_Client.isBluetooth && !BT_Server_Client.isServer)
					{
						engine.SetNextGameState(iGameDefines.GAME_STATE_OVER);
					}
					else
						engine.SetNextGameState(iGameDefines.GAME_STATE_WIN);
					
				}
				barHealth[0].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getY(), Anchor.BOTTOM_LEFT);
				barHealth[1].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getY(), Anchor.BOTTOM_RIGHT);
				
				barPanah[0].theSprite().setPosition(
					Utils.GetAnchorX(barPanah[0].theSprite().getWidth(), Anchor.BOTTOM_LEFT) + Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_LEFT].getX()),
					Utils.GetAnchorY(barPanah[0].theSprite().getHeight(), Anchor.BOTTOM_LEFT) - barHealth[0].theSprite().getHeight() - Utils.GetRatio(50));
				barPanah[1].theSprite()
					.setPosition(
						Utils.GetAnchorX(barPanah[1].theSprite().getWidth(), Anchor.BOTTOM_RIGHT) +
							Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_RIGHT].getX()),
						Utils.GetAnchorY(barPanah[1].theSprite().getHeight(), Anchor.BOTTOM_RIGHT) - barHealth[1].theSprite().getHeight() - Utils.GetRatio(50));
				

				mc.perlambat(perlambat1);
				mc2.perlambat(perlambat2);
			}
		}
		else
			enemy.onUpdate();
		

		
			if(BT_Server_Client.isBluetooth)
			{
				mc2.onUpdate();
				mc2.move(speedX, speedY);
			}
			else
				enemy.onUpdate();
			
		
		}
		
		
		
		if(!startItem)
		{
		
			if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_CAREER)
			{
				
				if(!stop_bar)
				{
					if(activeBar)
					switch (action)
					{
					case 0:
						if(bar_tenaga.theSprite().getWidth()  < iGameDefines.SPR_START_CARIEER[0].getW())
						{
							time+=5;
							bar_tenaga.theSprite().setWidth(time);	

						}
						else
							action = 1;
						break;

					case 1:
						if(bar_tenaga.theSprite().getWidth() > 0)
						{
							time-=5;
							bar_tenaga.theSprite().setWidth(time);	
						
						}
						else
							action =0;
						break;
					}
				}
				
			}
		}
						
	}
	
	public void SceneTouch(Scene arg0, TouchEvent arg1)
	{
		if (tutor.theSprite().hasParent())
		{
			if (arg1.isActionDown())
			{
				tutor.DetachSelf();
				gasing1.Play();

				if(GameEngineConfiguration.ModeSelected == MODE_CAREER)
				startItem=true;
				
				startGame = true;
				mc.setPlay(true);

				if(BT_Server_Client.isBluetooth)
					mc2.setPlay(true);
				else
					enemy.setPlay(true);
			}
		}
		
		
		
	}
	
	public void Touch(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea,
			float pTouchAreaLocalX, float pTouchAreaLocalY)
	{

		if (btnFight.theSprite().hasParent()) if (pSceneTouchEvent.isActionUp() && pTouchArea.equals(btnFight.theSprite()))
		{
//			if (BT_Server_Client.isBluetooth) 
//			{
//				engine.SceneAttach(scene, tutor);	
//			}
//			else
//			{
				
//				if(GameEngineConfiguration.is_tutor_enable)
//				{
//					engine.SceneAttach(scene, tutor);
//				}
				
//				gasing1.Play();
//				mc.setPlay(true);

				if(BT_Server_Client.isBluetooth)
				{
					mc2.setPlay(true);
					engine.server_Client.sendMessage("startGame");
				}
				else
				{
					enemy.setPlay(true);
				}

				vsBg.DetachSelf();
				for (int i = 0; i < 3; i++)
				{
					vsPanah[i].DetachSelf();
					if(i < 2)
						vsIcon[i].DetachSelf();
				}
				btnFight.DetachSelf();
				vsMata.DetachSelf();
								
				
				if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_SINGLE)
				{
					rec.theRect().detachSelf();
					
					if(GameEngineConfiguration.is_tutor_enable)
					engine.SceneAttach(scene, tutor);
				}else if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_CAREER)
				{
					
					engine.SceneAttach(scene, btnTenaga);
					
					if(GameEngineConfiguration.is_tutor_enable)
					engine.SceneAttach(scene, tutor_tenaga);
				
					
					activeBar = true;
				}
				else
				{
					rec.theRect().detachSelf();	
					
					gasing1.Play();

					startGame = true;
					mc.setPlay(true);
				}
			
			vsBg.DetachSelf();
			for (int i = 0; i < 3; i++)
			{
				vsPanah[i].DetachSelf();
				if (i < 2) vsIcon[i].DetachSelf();
			}
			btnFight.DetachSelf();
			vsMata.DetachSelf();
//			rec.theRect().detachSelf();
			
		}

//		}

		
		if (!vsBg.theSprite().hasParent() && !tutor.theSprite().hasParent())
			if (pSceneTouchEvent.isActionUp() && pTouchArea.equals(btnPause.theSprite()))
			{
				pause();
				if (BT_Server_Client.isBluetooth) 
				engine.server_Client.sendMessage("pause");
			}

		
		if(GameEngineConfiguration.ModeSelected == iGameDefines.MODE_CAREER)
		{
			if(pSceneTouchEvent.isActionDown() && pTouchArea.equals(btnTenaga.theSprite()))
			{
				stop_bar = true;
//				for(int i=0; i < iGameDefines.COUNT_TENAGA; i++)
				bar_tenaga.DetachSelf();
				
				btnTenaga.DetachSelf();
				tutor_tenaga.DetachSelf();
				rec.theRect().detachSelf();
				
//				engine.SceneAttach(scene, tutor);
				tutor.DetachSelf();
				
				startGame = true;
				
				Utils.TRACE("Prosentase Tenaga = "+getProsentasePower());
				Utils.TRACE("BAR height"+barHealth[0].theSprite().getHeight());
				setCareerMode();
				activeBar= false;
				startItem = true;
				stop_bar = false;
				
				gasing1.Play();

				mc.setPlay(true);

//				if(BT_Server_Client.isBluetooth)
//					mc2.setPlay(true);
//				else
//					enemy.setPlay(true);
				
			}
		}

	}
	
	public void keyBack(int keyCode, KeyEvent event)
	{
		if (!vsBg.theSprite().hasParent() && !tutor.theSprite().hasParent()) if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			pause();
		}
	}
	
	private void benturan()
    {
            benturan.Play();
           
            mc.setMove(false);
            mc.benturan();
           
            if (BT_Server_Client.isBluetooth)
            {
                mc2.setMove(false);
                mc2.benturan();
                
                    benturanX = (mc.getBody().getPosition().x + mc2.getBody().getPosition().x) / 2 * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
                    benturanY = (mc.getBody().getPosition().y + mc2.getBody().getPosition().y) / 2 * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
            }
            else
            {      
                enemy.benturan();
                    benturanX = (mc.getBody().getPosition().x + enemy.getBody().getPosition().x) / 2 * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
                    benturanY = (mc.getBody().getPosition().y + enemy.getBody().getPosition().y) / 2 * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
                    
//                    enemy.getEffect().theSprite().setVisible(false);
            }
           
            sprBenturan.SetPos(benturanX - sprBenturan.theSprite().getWidth() / 2, benturanY - sprBenturan.theSprite().getHeight() / 2);
            sprBenturan.theSprite().setVisible(true);
           
            anim_asap.SetPos(benturanX - Utils.GetRatio(80), benturanY - Utils.GetRatio(80));
            anim_asap.theSprite().setVisible(true);
            anim_asap.theSprite().animate(new long[] {100, 100, 100, 100}, false);
            
            engine.getEngine().registerUpdateHandler(new TimerHandler(1, new ITimerCallback() {
				
				public void onTimePassed(TimerHandler pTimerHandler) {
					// TODO Auto-generated method stub
					 mc.setMove(true);
                     if (BT_Server_Client.isBluetooth)
                     {
                             mc2.setMove(true);
                     }
				}
			}));
          
           
            engine.getEngine().registerUpdateHandler(new TimerHandler(0.3f, new ITimerCallback()
            {
                    public void onTimePassed(TimerHandler pTimerHandler)
                    {
                            sprBenturan.theSprite().setVisible(false);
                           
//                            if(!anim_asap.theSprite().isAnimationRunning())
                            anim_asap.theSprite().setVisible(false);
                            
                            if (BT_Server_Client.isBluetooth)
                            {
                                    if (BT_Server_Client.isServer)
                                    {
                                            bar1 = barHealth[0].theSprite().getHeight() - getDistance(mc.getBody(), mc.getBenturanX(), mc.getBenturanY()) / 5;
                                            bar2 = barHealth[1].theSprite().getHeight() - getDistance(mc2.getBody(), mc2.getBenturanX(), mc2.getBenturanY()) / 5;
                                           
                                            barHealth[0].theSprite().setHeight(bar1);
                                            barHealth[1].theSprite().setHeight(bar2);
                                           
                                            engine.server_Client.sendMessage("bar1," +bar1);
                                            engine.server_Client.sendMessage("bar2," +bar2);
                                    }
                            }
                            else
                            {
                                                            		
                            		barHealth[0].theSprite().setHeight(barHealth[0].theSprite().getHeight() - (getDistance(mc.getBody(), mc.getBenturanX(), mc.getBenturanY()) * iServer_Data.doubleAttack) / 5);
                                                                   
                                    barHealth[1].theSprite().setHeight(
                            	           barHealth[1].theSprite().getHeight() - (getDistance(enemy.getBody(), enemy.getBenturanX(), enemy.getBenturanY()) * iServer_Data.doubleAttack) / 5);
                                
                            }
                           
                            if (barHealth[0].theSprite().getHeight() <= 0)
                            {
                                    barHealth[0].theSprite().setHeight(0);
                                    scene.theScene().unregisterUpdateHandler(world);
                                    gasing1.Stop();
                                    engine.SetNextMessageState(0);

                            		Utils.TRACE("ffffffffff");
                                    if (BT_Server_Client.isBluetooth && !BT_Server_Client.isServer)
                                    {
                                            engine.SetNextGameState(iGameDefines.GAME_STATE_WIN);
                                    }                                              
                                    else
                                            engine.SetNextGameState(iGameDefines.GAME_STATE_OVER);
                            }
                            else if (barHealth[1].theSprite().getHeight() <= 0)
                            {
                                    barHealth[1].theSprite().setHeight(0);
                                    scene.theScene().unregisterUpdateHandler(world);
                                    gasing1.Stop();
                                    engine.SetNextMessageState(0);

                            		Utils.TRACE("aaaaaaaaaaaaaa");
                                    if (BT_Server_Client.isBluetooth && !BT_Server_Client.isServer)
                                    {
                                            engine.SetNextGameState(iGameDefines.GAME_STATE_OVER);
                                    }
                                    else
                                            engine.SetNextGameState(iGameDefines.GAME_STATE_WIN);
                                   
                            }
                           
                            barHealth[0].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_LEFT].getY(), Anchor.BOTTOM_LEFT);
                            barHealth[1].SetPos(SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getX(), SPRITE_GAME[SPRITE_GAME_BAR_HEALTH_RIGHT].getY(), Anchor.BOTTOM_RIGHT);
                           
                            barPanah[0].theSprite().setPosition(
                                    Utils.GetAnchorX(barPanah[0].theSprite().getWidth(), Anchor.BOTTOM_LEFT) + Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_LEFT].getX()),
                                    Utils.GetAnchorY(barPanah[0].theSprite().getHeight(), Anchor.BOTTOM_LEFT) - barHealth[0].theSprite().getHeight() - Utils.GetRatio(50));
                            barPanah[1].theSprite()
                                    .setPosition(
                                            Utils.GetAnchorX(barPanah[1].theSprite().getWidth(), Anchor.BOTTOM_RIGHT) +
                                                    Utils.GetRatio(SPRITE_GAME[SPRITE_GAME_BAR_PANAH_RIGHT].getX()),
                                            Utils.GetAnchorY(barPanah[1].theSprite().getHeight(), Anchor.BOTTOM_RIGHT) - barHealth[1].theSprite().getHeight() - Utils.GetRatio(50));
                           
                            if (BT_Server_Client.isBluetooth)
                            {
                                    if(BT_Server_Client.isServer)
                                    {
                                            float p1 = barHealth[0].theSprite().getHeight();
                                            float p2 = barHealth[1].theSprite().getHeight();
                                           
                                            mc.perlambat(p1);
                                            mc2.perlambat(p2);

                                            engine.server_Client.sendMessage("perlambat," +p1);
                                            engine.server_Client.sendMessage("perlambat," +p2);
                                    }
                            }
                            else
                            {
                                    mc.perlambat(barHealth[0].theSprite().getHeight());
                                    enemy.perlambat(barHealth[1].theSprite().getHeight());
                            }
                    }
            }));
           
    }
	
		
	private float getDistance(Body body, float x, float y)
	{
		return getDistance(body.getPosition().x
				* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
				body.getPosition().y
						* PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, x, y);
	}
	
	private float getDistance(float x1, float y1, float x2, float y2)
	{
		float dist_x = x1 - x2;
		float dist_y = y1 - y2;
		
		return (float) Math.sqrt((float) Math.pow(dist_x, 2)
				+ (float) Math.pow(dist_y, 2));
	}
	
	public static void reset()
	{		
		world.clearPhysicsConnectors();
		
		while (world.getBodies().hasNext())
		{
			world.destroyBody(world.getBodies().next());
		}
	}

	
	private float getProsentasePower()
	{
		return (float) time / iGameDefines.SPR_START_CARIEER[0].getW();
	}
	

	private void setCareerMode()
	{
		
		barHealth[0].theSprite().setHeight(barHealth[0].theSprite().getHeight() 
				* getProsentasePower());
		Utils.TRACE("prosentase "+barHealth[0].theSprite().getHeight() * getProsentasePower());
		barHealth[0].theSprite().setY(Utils.GetAnchorY(barHealth[0].theSprite().getHeight(), Anchor.BOTTOM_LEFT));
	}

	
	private void pause()
	{		
		scene.theScene().unregisterUpdateHandler(world);
		gasing1.Stop();
		engine.SetNextMessageState(0);
		engine.SetNextGameState(iGameDefines.GAME_STATE_PAUSE);
	}
	

	public static void exit()
	{
		
		scene.theScene().detachChildren();
		
	}


}
